package leecode

import (
	"sort"
	"strings"
)

func replaceWords(dictionary []string, sentence string) string {
	sort.Strings(dictionary)
	hashMap := make(map[string]int)
	arr := strings.Split(sentence, " ")
	result := make([]string, 0, len(sentence))
	for i := 0; i < len(dictionary); i++ {
		hashMap[dictionary[i]]++
	}
	for i := 0; i < len(arr); i++ {
		flag := 0
		for j := 0; j < len(dictionary); j++ {
			if len(dictionary[j]) > len(arr[i]) {
				continue
			}
			str := arr[i]
			temp := str[:len(dictionary[j])]
			if _, ok := hashMap[temp]; ok {
				flag = 1
				result = append(result, temp)
				break
			}
		}
		if flag == 0 {
			result = append(result, arr[i])
		}
	}
	return strings.Join(result, " ")
}
